package com.xc.utils.task.futures;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.dao.StockAllotmentMapper;
import com.xc.dao.StockBlockTradeMapper;
import com.xc.dao.StockMapper;
import com.xc.pojo.Stock;
import com.xc.pojo.StockAllotment;
import com.xc.service.IUserService;
import com.xc.stock.utils.Utils;
import com.xc.utils.DateTimeUtil;
import com.xc.utils.stock.BuyAndSellUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ForceSellFuturesTask {
    private static final Logger log = LoggerFactory.getLogger(ForceSellFuturesTask.class);
    @Autowired
    IUserService iUserService;
    @Autowired
    StockMapper stockMapper;
    @Autowired
    StockAllotmentMapper stockAllotmentMapper;

    /*指数强制平仓，每分钟执行一次*/
    @Scheduled(cron = "0 */1 * * * ?")
    public void banlanceUserFuturesPositionTaskV1() {
    	if(! Utils.enableScheduled()) {
    		return;
    	}
        dotask();
    }

    public void dotask() {
      //  this.iUserService.ForceSellFuturesTask();
    }

    /*指数强平提醒推送消息，每分钟检测一次*/
    @Scheduled(cron = "0 */1 * * * ?")
    public void banlanceUserFuturesPositioMessage() {
    	if(! Utils.enableScheduled()) {
    		return;
    	}
       // this.iUserService.ForceSellFuturesMessageTask();
    }

    /*期货走势图定时任务*/
    @Scheduled(cron = "0 0/1 0-23 * * MON-FRI")
    public void qh1() {
    	if(! Utils.enableScheduled()) {
    		return;
    	}
//        boolean am = false;
//        boolean pm = false;
//        try {
//            am = BuyAndSellUtils.isTransTime("0:01", "12:59");
//            pm = BuyAndSellUtils.isTransTime("12:59", "23:59");
//        } catch (Exception e) {
//            log.error("= {}", e);
//        }
//        log.info("qh1-am = {}  pm = {}", Boolean.valueOf(am), Boolean.valueOf(pm));
//        if (am || pm) {
//            log.info("====={} =====", DateTimeUtil.dateToStr(new Date()));
//            this.iUserService.qh1();
//            log.info("====={} =====", DateTimeUtil.dateToStr(new Date()));
//        }
    }

    /*更新数据库股票名，每天凌晨一点更新一次*/
    @Scheduled(cron = "0 0 3 * * ?")
    public void updateStockName() {
        ArrayList<Map> list = new ArrayList<>();
        for (int i = 0; i < 99; i++) {
            String url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?" +
                    "page=" + i +
                    "&num=100" +
                    "&sort=symbol" +//排序的列
                    "&asc=1" +//1：升序  0：降序
                    "&node=" + "sz_a" +
                    "&symbol=" +
                    "&_s_r_a=init";//以symbol升序时 默认为init 根据其他排序时均为sort
            //发送请求
            String resultStr = HttpUtil.get(url);
            JSONArray resultJson = JSONArray.parseArray(resultStr);
            List<Map> jsonObjects = JSONObject.parseArray(resultJson.toString(), Map.class);
            list.addAll(jsonObjects);
            if (resultJson.size() == 0 ){
                break;
            }
        }

        List<Stock> stocks = stockMapper.findStockList();
        try {
            stocks.forEach(stock -> {
                List<Map> code = list.stream().filter(map -> map.get("code").equals(stock.getStockCode())).collect(Collectors.toList());
                if (code.size() != 0 && !(code.get(0).get("name").toString()).equals(stock.getStockName())) {
                    stock.setStockName(code.get(0).get("name").toString());
                    stockMapper.stockByStockCode(stock.getStockCode(), code.get(0).get("name").toString());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
